package tron;

/*package tron;

 import java.io.*;
 import java.net.*;

 public class Server implements Runnable{
 private ServerSocket serverSoq = null;
 private int port;
 private Field field;
 public Server(int port, Field field){
 this.port = port;
 this.field = field;
 }
 public void serverUp() {
 try {
 serverSoq = new ServerSocket(port);
 while (true) {
 Socket client = serverSoq.accept();
 ObjectInputStream  in = new ObjectInputStream (client.getInputStream());
 Request rq = (Request) in.readObject();
 ObjectOutputStream  out = new ObjectOutputStream (client.getOutputStream());
 Response rs = execute(rq);
 out.writeObject(rs);
 client.close();
 }
 } catch (Exception exp) {
 exp.printStackTrace();
 }
 }
 public void run(){
 serverUp();
 }
 }
 */

import java.net.*;
import java.io.*;

public class Server {
    int timeout = 500;
    ObjectInputStream in;
    ObjectOutputStream out;
    Field field;
    FieldPanel fieldPanel;
    Socket socket;

    public Server(Game game, Field field, FieldPanel fieldPanel) {
	this.field = field;
	this.fieldPanel = fieldPanel;

	int port = 6666;
	try {
	    ServerSocket ss = new ServerSocket(port);
	    System.out.println("Waiting for a client...");
	    socket = ss.accept();
	    System.out
		    .println("Got a client :) ... Finally, someone saw me through all the cover!");
	} catch (Exception x) {
	    x.printStackTrace();
	}

    }

    public void startServer() {

	try {
	    in = new ObjectInputStream(socket.getInputStream());
	    out = new ObjectOutputStream(socket.getOutputStream());
	    while (true) {
		while (in.available() != -1) {
		    Snake snake = (Snake) in.readObject();
		    System.out.println("Server " + snake);
		}
		field.update();
		out.writeObject(field);
		out.flush();

		fieldPanel.repaint();
		int winner = field.winner();
		if (winner != -1) {
		    if (winner == 0)
			System.out.println("Draw");
		    else
			System.out.println("Winner " + winner);
		    return;
		}
		Thread.sleep(timeout);
	    }
	} catch (Exception x) {
	    x.printStackTrace();
	    System.exit(1);
	}
    }
}